import { createRouter,createWebHashHistory} from 'vue-router';
import home from "@/home.vue";
import finished from "@/finished.vue";
import add from "@/add.vue";
import AcceptanceRecord from "@/AcceptanceRecord.vue";
import login from "@/login.vue";
import AddUserForm from "@/AddUserForm.vue";
import { checkTokenExpired } from '@/js/api';
import { ElMessage } from 'element-plus';

const router = createRouter({
        history:createWebHashHistory(),
    routes: [
        {
            path: '/',
            component:login
        },
        {
            path: '/login',
            component:login
        },
        {
            path: '/home',
            component: home
        },
        {
            path: '/finished',
            component: finished
        },
        {
            path: '/add',
            component: add
        },
        {
            path: '/AcceptanceRecord',
            component: AcceptanceRecord
        },
        {
            path: '/addUser',
            component: AddUserForm
        }
    ]
});

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    // 如果是访问登录页面或首页，直接放行
    if (to.path === '/login' || to.path === '/') {
        next();
        return;
    }
    
    // 检查token是否存在
    const token = localStorage.getItem('token');
    if (!token) {
        ElMessage.error('请先登录');
        next('/login');
        return;
    }
    
    try {
        // 检查token是否过期
        const { expired } = await checkTokenExpired();
        console.log('Token过期状态:', expired);
        
        if (expired) {
            // 清除本地存储的token和用户信息
            localStorage.removeItem('token');
            localStorage.removeItem('user'); // 修正：应该是'user'而不是'userInfo'
            ElMessage.error('登录已过期，请重新登录');
            next('/login');
            return;
        }
        
        next();
    } catch (error) {
        console.error('路由守卫检查token出错:', error);
        // 发生错误时，为安全起见，重定向到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        ElMessage.error('登录状态验证失败，请重新登录');
        next('/login');
    }
});

export default router;